package net.lainiao.zhihu.backserver;

import net.lainiao.zhihu.common.Common;
import net.lainiao.zhihu.dao.ZhihuhuatipageMapper;
import net.lainiao.zhihu.dao.ZhihuhuatipagelinksMapper;
import net.lainiao.zhihu.model.Zhihuhuatipage;
import net.lainiao.zhihu.model.Zhihuhuatipagelinks;
import org.springframework.context.ApplicationContext;
import net.lainiao.zhihu.reptitle.ZhihuhualinksHtml;

import java.util.List;

/**
 * Created by Administrator on 2016/1/15.
 */
public class ZhihuhuatiPageTask extends ZhihuTask implements Runnable {

    public ZhihuhuatiPageTask(ApplicationContext context) {
        super(context);
    }

    public void run() {
        ZhihuhuatipageMapper zhihuhuatipageMapper = context.getBean(ZhihuhuatipageMapper.class);
        ZhihuhuatipagelinksMapper zhihuhuatipagelinksMapper = context.getBean(ZhihuhuatipagelinksMapper.class);
        Zhihuhuatipage zhihuhuatipage=null;
        while (status == 1) {
            zhihuhuatipage = zhihuhuatipageMapper.getNext();
            if (zhihuhuatipage == null) {
                break;
            }
            try {
                List<String> urls = ZhihuhualinksHtml.getLinks(zhihuhuatipage.getUrl());
                for (String str:urls) {
                    String tem="http://www.zhihu.com"+str;
                    Zhihuhuatipagelinks model=new Zhihuhuatipagelinks();
                    model.setId(Common.getNewUUID());
                    model.setStatus(0);
                    model.setUrl(tem);
                    model.setZhhtpId(zhihuhuatipage.getId());
                    zhihuhuatipagelinksMapper.insert(model);
                    Thread.sleep(500);
                }
                zhihuhuatipage.setStatus(1);
                zhihuhuatipageMapper.updateByPrimaryKey(zhihuhuatipage);

            } catch (Exception e) {
                e.printStackTrace();
                if(zhihuhuatipage!=null){
                    zhihuhuatipage.setStatus(2);
                    zhihuhuatipageMapper.updateByPrimaryKey(zhihuhuatipage);
                }
            }
        }
    }
}
